package com.tmsps.neframework.jpa.base;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import com.alibaba.druid.pool.DruidDataSource;
import com.tmsps.neframework.jpa.annotation.DataSource;
import com.tmsps.neframework.jpa.core.CoreQueue;

public class DatabaseInfo {

	private static DruidDataSource dataSource = null;
	private static Dialect dialect = null;
	public static boolean showSql = false;

	static {
		// 加载DataSource
		init();
	}

	public static void init() {
		// 初始化DataSource
		for (Class<?> clazz : CoreQueue.allClasses) {
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
				if (!method.isAnnotationPresent(DataSource.class)) {
					continue;
				}
				try {
					DataSource dataSourceAnnotation = method.getAnnotation(DataSource.class);
					DatabaseInfo.showSql = dataSourceAnnotation.showSql();
					dataSource = (DruidDataSource) method.invoke(clazz.newInstance());
				} catch (Exception e) {
					e.printStackTrace();
				}

			} // #for method

		}

		if (dataSource == null) {
			throw new RuntimeException("请在获取数据库连接池的函数上加上 @DataSource 注解.");
		}

	}

	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return conn;
	}

	public static DruidDataSource getDataSource() {
		return dataSource;
	}

	public static Dialect getDialect() {
		if (dialect == null) {
			String driverClassName = getDataSource().getDriverClassName();

			if (driverClassName.contains("derby")) {
				dialect = Dialect.derby;
			} else if (driverClassName.contains("mysql")) {
				dialect = Dialect.mysql;
			} else {
				String dbs = "";
				for (Dialect db : Dialect.values()) {
					dbs += db.dialect + " ";
				}
				throw new RuntimeException("NE_ORM 不支持该数据库.只支持:" + dbs);
			}
		}
		return dialect;
	}

	public enum Dialect {
		derby("derby"), mysql("mysql");
		private Dialect(String dialect) {
			this.dialect = dialect;
		}

		public String toString() {
			return dialect.toString();
		}

		private String dialect;
	}
}
